#include "transcodewidget.h"
#include <QDir>
#include <QFileInfo>
#include <QPixmap>

TranscodeWidget::TranscodeWidget(QWidget* parent) : QWidget(parent) {

    initWidgets();
    initLayout();
    this->applyStyle();
    //connect(&progressTimer, &QTimer::timeout, this, &TranscodeWidget::updateProgress);
    this->setFixedSize (700,900);
}

TranscodeWidget::~TranscodeWidget() = default;

void TranscodeWidget::initWidgets() {
    //日期按钮
     date_button=new QPushButton("",this);

      this->transcode=new TransCodeVideo();
      connect(this->transcode,&TransCodeVideo::sendX,this,&TranscodeWidget::reciveX);
      this->con=MyControl::getInstance();

    // 解码方式
    decodeCombo = new QComboBox(this);
    decodeCombo->addItems({"mp4", "avi", "wmv"});

    // 路径存储
    pathLineEdit = new QLineEdit(this);
    browseButton = new QPushButton("+", this);
    connect(browseButton, &QPushButton::clicked, this, &TranscodeWidget::onBrowsePath);

    // 进度条
//    progressBar = new QProgressBar(this);
//    progressBar->setVisible(false);
    this->seekSlider = new QSlider(Qt::Horizontal, this); // 显式指定水平方向






    // 操作按钮
    confirmButton = new QPushButton("确定", this);
    returnButton = new QPushButton("返回", this);
    connect(confirmButton, &QPushButton::clicked, this, &TranscodeWidget::startTranscoding);

    connect(returnButton, &QPushButton::clicked, this, &TranscodeWidget::ret);

    listWidget=new QListWidget(this);
    listWidget->setFlow(QListView::LeftToRight);
    //this->listWidget->setViewMode(QListView::IconMode);
    this->listWidget->setFixedSize(1100,800);
    listWidget->setMinimumWidth(150);
    listWidget->setFont(QFont("宋体",12));

    listWidget->setIconSize(QSize(200,250));
    QPalette pal=listWidget->palette();
    pal.setColor(QPalette::Base,Qt::transparent);//底色透明
    listWidget->setPalette(pal);
    listWidget->setAutoFillBackground(false);
    listWidget->setStyleSheet("QListWidget{border:none;}");
    listWidget->setDragEnabled(false);//禁止拖拽



    this->SelectDataBase();


    //connect(this->returnButton,&QPushButton::clicked,this,&TranscodeWidget::onRetClicked);
}

void TranscodeWidget::initLayout() {


    // 标题
    QHBoxLayout*title_layout=new QHBoxLayout();
    title_layout->setContentsMargins(0, 0, 0, 0);
    QLabel* titleLabel = new QLabel("转码界面", this);
    title_layout->addWidget(titleLabel);
    titleLabel->setAlignment(Qt::AlignCenter);
    titleLabel->setStyleSheet("font-size: 20px; font-weight: bold;");




    // 日期输入行
    QHBoxLayout* dateLayout = new QHBoxLayout();
    dateLayout->setContentsMargins(0, 0, 0, 0);
    dateLayout->addWidget(new QLabel("请输入日期"));
    dateLayout->addWidget(date_button);

    connect(date_button, &QPushButton::clicked, this, &TranscodeWidget::showCalender);

        // 初始化日历控件
    calendarWidget = new QCalendarWidget(this);
    calendarWidget->setWindowFlags(Qt::Popup);
    calendarWidget->hide();
    connect(calendarWidget, &QCalendarWidget::activated, this, &TranscodeWidget::selectCalender);


    // 视频列表
    QHBoxLayout*listLayout=new QHBoxLayout();
    listLayout->addWidget(listWidget);
    listWidget->setFixedSize(600, 200); // 宽度 300，高度 400



    // 转码格式行（解码方式）
    QHBoxLayout* decodeLayout = new QHBoxLayout();
    decodeLayout->addWidget(new QLabel("解码方式"));
    decodeLayout->addWidget(decodeCombo);

    // 路径存储行
    QHBoxLayout* pathLayout = new QHBoxLayout();
    pathLayout->addWidget(new QLabel("路径存储"));
    pathLayout->addWidget(pathLineEdit);
    pathLayout->addWidget(browseButton);


    // 进度条
    QHBoxLayout*BarLayout=new QHBoxLayout();
    BarLayout->addWidget(this->seekSlider);
    BarLayout->setContentsMargins(0,0,0,20);

    // 按钮行
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    //buttonLayout->setContentsMargins(0,0,0,300);
    buttonLayout->addWidget(confirmButton);
    buttonLayout->addWidget(returnButton);
    buttonLayout->setSpacing(30);



    QVBoxLayout* mainLayout = new QVBoxLayout(this);
         // 垂直间距
    mainLayout->setContentsMargins(30, 100, 30, 200); // 四周边距
    mainLayout->setSpacing(30);

    mainLayout->addLayout(title_layout);
    mainLayout->addLayout(dateLayout);
    mainLayout->addLayout(listLayout);
    mainLayout->addLayout(decodeLayout);
    mainLayout->addLayout(pathLayout);
    mainLayout->addLayout(BarLayout);
    mainLayout->addLayout(buttonLayout);


    setLayout(mainLayout);
}





void TranscodeWidget::onBrowsePath() {
    QString directoryPath = QFileDialog::getExistingDirectory(nullptr, "选择文件夹", "../video", QFileDialog::ShowDirsOnly);
    this->pathLineEdit->setText(directoryPath);
}

void TranscodeWidget::startTranscoding() {

    QList<QListWidgetItem*> selectedItems = listWidget->selectedItems();
        if (selectedItems.isEmpty()) {
            // 没有选中任何项，给出提示
            QMessageBox::warning(nullptr,"警告","请选择要转码的视频！");
            qDebug() << "请选择要转码的视频！";
            return;
        }


        QString decodeFormat = decodeCombo->currentText();
            // 获取存储路径
            QString savePath = pathLineEdit->text();
            if (savePath.isEmpty()) {
                // 存储路径为空，给出提示

                QMessageBox::warning(nullptr,"警告","路径为空");
                qDebug() << "请选择存储路径！";
                return;
            }

            // 遍历选中的列表项
               for (QListWidgetItem* item : selectedItems) {


                   this->seekSlider->setValue(0);
                   this->transcode->setX(0);
                   // 获取关联的视频对象
                       // 调用转码函数进行转码
                       QString itemText = "../video/"+item->text()+".H264";

                       this->videoIndex=item->data(Qt::UserRole).toInt ();

                       qDebug()<<"videoIndex="<<videoIndex;
                       qDebug()<<itemText;


                       QString type=decodeCombo->currentText();
                       QFileInfo fileInfo(this->selectVideos[videoIndex]->getVideo_path());

                       if(fileInfo.suffix()==type)
                        {

                           QMessageBox::information(this,"提示","所选的视频格式和当前的一样");
                           return ;
                        }//如果是要转的种类是一样的，就不用转了 就不用转了


                       transcode->openH264File(itemText.toStdString().c_str());

                       seekSlider->setRange(0,this->selectVideos[videoIndex]->getDuration()-12);//进度条设置
                       qDebug()<<"this->selectVideos[videoIndex]->getDuration()-12"<<this->selectVideos[videoIndex]->getDuration()-12;



                       QString videopath=savePath+"/"+item->text()+"."+type;
                       qDebug()<<videopath;
                       transcode->tranceToMp4(videopath.toStdString().c_str());
                       seekSlider->setValue(this->x);
                       seekSlider->update();



                       //把转码的视频插入到数据库中
                       this->model=this->con->getModel("video_file");
                        QString sql=QString("insert into video_files (user_id,video_path,video_name,duration,video_img_path) VALUES (%1,'%2','%3','%4','%5');")
                               .arg(id)
                               .arg(videopath)
                               .arg(item->text())
                               .arg(this->selectVideos[videoIndex]->getDuration())
                               .arg(this->selectVideos[videoIndex]->getVideo_img_path());
                       qDebug()<<sql;

                       this->model->insetVideoInfo((char *)sql.toStdString().c_str());
               }


    //seekSlider->setValue(0);

               int res=QMessageBox::information(nullptr,"提示","转码成功");
               if(res)
               {
                   this->seekSlider->setValue(0);
                   this->transcode->init();
               }
              // this->seekSlider->setValue(0);



}

//void TranscodeWidget::updateProgress() {
//    static int value = 0;
//    value += 5;

//    if (value >= 100) {
//        progressTimer.stop();
//        // 转码完成逻辑
//    }
//}


void TranscodeWidget::showCalender()
{
    QPoint pos=date_button->mapToGlobal(QPoint(0,date_button->height()));
    this->calendarWidget->move(pos);
    this->calendarWidget->show();
}

void TranscodeWidget::selectCalender(const QDate &date)
{
    this->seekSlider->setValue(0);
    QString dateStr = date.toString("yyyy-MM-dd");
    date_button->setText(dateStr);
    this->calendarWidget->hide();



    QList<Video*> filteredVideos;
    for (Video* video : videos)
    {

           QDate videoDate = video->extractDateFromName();
           QString videoDateStr=videoDate.toString("yyyy-MM-dd");
           qDebug()<<"videoDateStr="<<videoDateStr;

           if (videoDateStr == dateStr)
           {

               filteredVideos.push_back(video);
           }
     }


    if (filteredVideos.isEmpty()) {
            QMessageBox::information(this, "提示", "按照该日期查询，未找到相关视频。");
        }

    this->selectVideos=filteredVideos;
    this->listWidget->clear();
    QList<Video*>::iterator iter=filteredVideos.begin();
    int index=0;
       while(iter!=filteredVideos.end())
       {
           QListWidgetItem *item=new QListWidgetItem(QIcon((*iter)->getVideo_img_path().toStdString().c_str()),(*iter)->getVideo_name().toStdString().c_str(),this->listWidget);
           item->setData(Qt::UserRole, index); // 设置当前视频的索引作为用户数据
           listWidget->addItem(item);
           iter++;
           index++;
       }

}

void TranscodeWidget::ret()
{
    emit ToMain();
}

void TranscodeWidget::reciveX(int x)
{
    this->x=x;
}



void TranscodeWidget::SelectDataBase()//把数据从数据库中查找出来
{
    this->model=this->con->getModel("video_file");
    QString sql=QString("select *from video_files where user_id=%1 ORDER BY video_files.video_id DESC;").arg(id);
    this->videos=this->model->getVideoInfo((char *)sql.toStdString().c_str());

    this->listWidget->clear();
        this->selectVideos=this->videos;
        QList<Video*>::iterator iter=videos.begin();
        int index=0;
        while(iter!=videos.end())
        {
            QListWidgetItem *item=new QListWidgetItem(QIcon((*iter)->getVideo_img_path().toStdString().c_str()),(*iter)->getVideo_name().toStdString().c_str(),this->listWidget);
            item->setData(Qt::UserRole, index); // 设置 videoIndex 作为用户数据
            listWidget->addItem(item);
            index++;
            iter++;
        }


}

void TranscodeWidget::showEvent(QShowEvent *event)
{
        this->SelectDataBase();
        QWidget::showEvent(event);
}









void TranscodeWidget::applyStyle()
{
    // 全局样式
    setStyleSheet(R"(
        QWidget {
            background-color: #ecf0f1;
            font-family: "Microsoft YaHei";
        }

        /* 增大标题样式 */
        QLabel#titleLabel {
            font-size: 30px;
            font-weight: bold;
            color: #2c3e50;
            margin-bottom: 20px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 8px;
        }

        QGroupBox {
            border: 1px solid #bdc3c7;
            border-radius: 10px;
            margin-top: 15px;
            padding: 15px;
        }

        QGroupBox::title {
            subcontrol-origin: margin;
            left: 15px;
            padding: 0 8px;
            font-size: 16px;
            font-weight: bold;
        }

        QPushButton {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 6px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        /* 下拉框优化 */
        QComboBox {
            border: 2px solid #bdc3c7;
            border-radius: 8px;
            padding: 8px 24px 8px 12px;
            font-size: 14px;
            background: white;
            background-image: url(:/icons/down_arrow.png);
            background-repeat: no-repeat;
            background-position: right 8px center;
            background-size: 16px;
        }

        QComboBox:hover {
            border-color: #3498db;
        }

        QComboBox:focus {
            border-color: #3498db;
            outline: none;
            box-shadow: 0 0 8px rgba(52, 152, 219, 0.3);
        }

        QComboBox::drop-down {
            border: none;
            width: 24px;
        }

        QComboBox::down-arrow {
            image: none;
        }

        /* 进度条样式优化 */
        QSlider::groove:horizontal {
            border: 1px solid #bdc3c7;
            background: #f5f5f5;
            height: 10px;
            border-radius: 5px;
            margin: 2px 0;
        }

        QSlider::sub-page:horizontal {
            background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0,
                                        stop: 0 #3498db, stop: 1 #2980b9);
            border: 1px solid #2980b9;
            height: 10px;
            border-radius: 5px;
        }

        QSlider::add-page:horizontal {
            background: #f5f5f5;
            border: 1px solid #bdc3c7;
            height: 10px;
            border-radius: 5px;
        }

        QSlider::handle:horizontal {
            background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                        stop: 0 #ffffff, stop: 1 #e0e0e0);
            border: 1px solid #bdc3c7;
            width: 16px;
            height: 16px;
            border-radius: 8px;
            margin: -3px 0;
        }

        QSlider::handle:horizontal:hover {
            background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                        stop: 0 #f0f0f0, stop: 1 #d0d0d0);
        }

        QSlider::handle:horizontal:pressed {
            background: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1,
                                        stop: 0 #d0d0d0, stop: 1 #b0b0b0);
        }

        QPushButton:hover {
            background-color: #2980b9;
        }

        QPushButton:pressed {
            background-color: #216699;
        }

        QLineEdit {
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 6px;
        }

        QListWidget {
            background-color: white;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 8px;
        }

        QListWidget::item {
            padding: 8px;
            border-bottom: 1px solid #ecf0f1;
        }

        QListWidget::item:hover {
            background-color: #f0f3f5;
        }
    )");

    // 日期按钮样式
    date_button->setStyleSheet(R"(
        QPushButton {
            background-color: #2ecc71;
            padding: 10px 30px;
            border-radius: 8px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #27ae60;
        }
    )");

    // 返回按钮样式
    returnButton->setStyleSheet(R"(
        QPushButton {
            background-color: #e74c3c;
            padding: 10px 30px;
            border-radius: 8px;
            font-size: 14px;
        }
        QPushButton:hover {
            background-color: #c0392b;
        }
    )");

    // 设置标题ID
   // titleLabel->setObjectName("titleLabel");
}
